package com.lengxf.netty.config;

import com.lengxf.netty.config.initializer.WebSocketServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Slf4j
@Component
public class NettyServer {

    private final static int SERVER_PORT = 30001;

    private ChannelFuture serverChannelFuture;

    private final static EventLoopGroup bossGroup = new NioEventLoopGroup(1);

    private final static EventLoopGroup workerGroup = new NioEventLoopGroup(10);

    @Resource
    private WebSocketServerInitializer webSocketServerInitializer;


    @PostConstruct
    public void start() throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(webSocketServerInitializer);
        serverChannelFuture = bootstrap.bind(new InetSocketAddress(SERVER_PORT)).sync();
    }


    @PreDestroy
    public void stop() {
        serverChannelFuture.channel().close();
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}
